﻿// lindexi
// 10:58

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Threading;
using System.Threading.Tasks;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Networking.BackgroundTransfer;
using Windows.Storage;
using Windows.Storage.Pickers;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

// “内容对话框”项模板在 http://go.microsoft.com/fwlink/?LinkId=234238 上进行了说明

namespace SplitViewOptions.BusinessControl
{
    public sealed partial class DownloadContentDialog : ContentDialog
    {
        public DownloadContentDialog(string str)
        {
            this.InitializeComponent();
            _url = str;
        }

        public async void Download(string str, string filename)
        {
            if (string.IsNullOrEmpty(nameboxurl.Text))
            {
                return;
            }
            FolderPicker folderPicker = new FolderPicker
            {
                SuggestedStartLocation = PickerLocationId.Downloads,
                ViewMode = PickerViewMode.Thumbnail
            };
            //todo:本句你要做的文件类型？
            folderPicker.FileTypeFilter.Add("*");
            StorageFolder folder = await folderPicker.PickSingleFolderAsync();
            if (folder != null)
            {
                StorageFile file = await folder.CreateFileAsync(filename, CreationCollisionOption.GenerateUniqueName);
                Uri durl = new Uri(str, UriKind.RelativeOrAbsolute);
                _downloadOperation = _backgroundDownloader.CreateDownload(durl, file);
                Progress<DownloadOperation> progress = new Progress<DownloadOperation>(ProgressChanged);
                cancellationToken = new CancellationTokenSource();
                try
                {
                    Statustext.Text = "Initializing...";
                    await _downloadOperation.StartAsync().AsTask(cancellationToken.Token, progress);
                }
                catch (TaskCanceledException)
                {
                    await _downloadOperation.ResultFile.DeleteAsync();
                    _downloadOperation = null;
                }
            }
        }

        private BackgroundDownloader _backgroundDownloader = new BackgroundDownloader();
        private DownloadOperation _downloadOperation;
        private string _url;
        private CancellationTokenSource cancellationToken;

        private void ContentDialog_PrimaryButtonClick(ContentDialog sender, ContentDialogButtonClickEventArgs args)
        {
            string name = HtmlUsedFunction.getnamebyurl(tboxurl.Text);
            nameboxurl.Text = name;
            Download(tboxurl.Text, name);
            args.Cancel = true;
        }

        private void ContentDialog_SecondaryButtonClick(ContentDialog sender, ContentDialogButtonClickEventArgs args)
        {
        }

        private void ProgressChanged(DownloadOperation downloadOperation)
        {
            //todo：无法获取下载大小 ——林德熙
            int progress =
                (int)
                (100*
                 ((double) downloadOperation.Progress.BytesReceived/
                  (double) downloadOperation.Progress.TotalBytesToReceive));
            Statustext.Text = string.Format("{0} of {1} kb. downloaded - %{2} complete.",
                downloadOperation.Progress.BytesReceived/1024, downloadOperation.Progress.TotalBytesToReceive/1024,
                progress);
            switch (downloadOperation.Progress.Status)
            {
                case BackgroundTransferStatus.Running:
                {
                    break;
                }
                case BackgroundTransferStatus.PausedByApplication:
                {
                    break;
                }
                case BackgroundTransferStatus.PausedCostedNetwork:
                {
                    break;
                }
                case BackgroundTransferStatus.PausedNoNetwork:
                {
                    break;
                }
                case BackgroundTransferStatus.Error:
                {
                    Statustext.Text = "An error occured while downloading.";
                    break;
                }
            }
            if (progress >= 100)
            {
                downloadOperation = null;
            }
        }

        private void tboxurl_LostFocus(object sender, RoutedEventArgs e)
        {
            nameboxurl.Text = "";
            string name = HtmlUsedFunction.getnamebyurl(tboxurl.Text);
            nameboxurl.Text = name;
        }

        private void nameboxurl_GotFocus(object sender, RoutedEventArgs e)
        {
        }
    }
}